package com.yangfan.thread.thread_wangwenjun06;

import java.util.List;


public class ThreadLifeCycleObserver implements LifeCycleListener {

    //锁
    private static final Object LOCK = new Object();

    /**
     * 假设一个并发查询  根据 id 进行查询 方法，一个线程进行一个查询  然后监控 每个线程的 生命周期
     * @param ids
     */
    public void concurrentQuery(List<String> ids) {

        //容错判断
        if (ids == null || ids.isEmpty())
            return;


        ids.stream().forEach(id -> new Thread(new ObservableRunnable(this) {

            @Override
            public void run() {
                try {

                    notifyChange(new RunnableEvent(RunnableState.RUNNING, Thread.currentThread(), null));
                    System.out.println("query for the id " + id);

                    Thread.sleep(1000L);

                    notifyChange(new RunnableEvent(RunnableState.DONE, Thread.currentThread(), null));

                } catch (Exception e) {
                    notifyChange(new RunnableEvent(RunnableState.ERROR, Thread.currentThread(), e));
                }
            }
        }, id).start());
    }


    /**
     * 实现触发事件
     * @param event
     */
    @Override
    public void onEvent(ObservableRunnable.RunnableEvent event) {

        synchronized (LOCK) {
            System.out.println("The runnable [" + event.getThread().getName() + "] data changed and state is [" + event.getState() + "]");
            if (event.getCause() != null) {
                System.out.println("The runnable [" + event.getThread().getName() + "] process failed.");
                event.getCause().printStackTrace();
            }
        }

    }




}